#include "TxDrawingElement.h"
#include "TxResourceManager.h"
#include "s3eTimer.h"
#include <limits>

TxDrawingElement::~TxDrawingElement()
{
	/*if(sprite)
	{
		delete sprite;
	}*/
}

TxDrawingElement* TxDrawingElement::createDrawingElement(char* file)
{
	TxDrawingElement* newElement	= new TxDrawingElement();
	newElement->sprite				= TxResourceManager::getResoureceManager()->addImage(file);
	newElement->initialize();

	return newElement;
}

void TxDrawingElement::initialize()
{
	position			= CIwFVec2(0, 0);
	destinationPoint	= CIwFVec2(0, 0);
	basePoint			= CIwFVec2(sprite->GetWidth() / 2, sprite->GetHeight() / 2);
	movementTimeLeft	= 0;
	lastDrawingTime		= s3eTimerGetUTC();
	visibility			= true;
}

void TxDrawingElement::drawElement()
{
	moveElement();
	Iw2DDrawImage(sprite, position - basePoint);
	lastDrawingTime = s3eTimerGetUTC();
}

void TxDrawingElement::moveToPoint(CIwFVec2 point, uint32 timeMS)
{
	destinationPoint	= point;
	movementTimeLeft	= timeMS;
}

void TxDrawingElement::moveElement()
{
	if(movementTimeLeft > 0)
	{
		uint32 timeFromLastDrawing = s3eTimerGetUTC() - lastDrawingTime;
		float step = static_cast<float>(timeFromLastDrawing) / static_cast<float>(movementTimeLeft);
		movementTimeLeft -= timeFromLastDrawing;
		position += CIwFVec2((destinationPoint.x - position.x) * step, (destinationPoint.y - position.y) * step);

		if(movementTimeLeft < 100)
		{
			uint32 y = movementTimeLeft;
		}

		if(movementTimeLeft > UINT_MAX - 10000)
		{
			movementTimeLeft = 0;
			position = destinationPoint;
		}
	}
}